package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class CommentApiImpl implements CommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //根据动态id和互动类型，分页查询互动数据
    public List<Comment> findComments(String movementId, Integer commentType, Integer page,
                                      Integer pagesize) {
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(movementId))
                                    .and("commentType").is(commentType);
        Query query = Query.query(criteria)
                .skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        return mongoTemplate.find(query,Comment.class);
    }

    //保存互动数据
    public Integer save(Comment comment) {
        ObjectId movementId = comment.getPublishId();
        //1、根据动态id，查询动态
        Movement movement = mongoTemplate.findById(movementId, Movement.class);
        //2、设置comment中的publishUserId属性
        comment.setPublishUserId(movement.getUserId());
        //3、保存Comment到数据库中
        mongoTemplate.save(comment);

        //4、更新动态表中的评论数量  update xxx set commentCount = commentCount+1 where id =?
        Criteria criteria = Criteria.where("id").is(movementId);
        Query query = Query.query(criteria);
        //更新字段
        Update update = new Update();
        if(comment.getCommentType() == 1) {
            update.inc("likeCount",1); //对指定字段，增加响应的数值
        }else if(comment.getCommentType() == 2) {
            update.inc("commentCount",1); //对指定字段，增加响应的数值
        }else {
            update.inc("loveCount",1); //对指定字段，增加响应的数值
        }
        //更新配置
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//设置更新之后，返回最新记录
        //更新
        Movement modify = mongoTemplate.findAndModify(query, update, options, Movement.class);//查询条件query，更新对象update，更新配置，实体类.class
        //返回最新的更新数量
        if(comment.getCommentType() == 1) {
            return modify.getLikeCount();
        }else if(comment.getCommentType() == 2) {
            return modify.getCommentCount();
        }else {
            return modify.getLoveCount();
        }
    }

    //判断互动数据是否存在
    public Boolean hasComment(String movementId, Long userId, Integer commentType) {
        Criteria criteria = Criteria.where("publishId").is(new ObjectId(movementId))
                                    .and("commentType").is(commentType)
                                    .and("userId").is(userId);
        Query query = Query.query(criteria);

        //获取数据是否存在(true-存在，false：不存在)
        return mongoTemplate.exists(query, Comment.class);
    }

    //删除互动数据，返回删除之后的互动总数
    public Integer delete(String movementId, Long userId, Integer commentType) {
        //1、删除互动表Comment中的数据
        Criteria commentCriteria = Criteria.where("publishId").is(new ObjectId(movementId))
                .and("commentType").is(commentType)
                .and("userId").is(userId);
        Query commentQuery = Query.query(commentCriteria);
        mongoTemplate.remove(commentQuery,Comment.class);

        Criteria criteria = Criteria.where("id").is(new ObjectId(movementId));
        Query query = Query.query(criteria);
        //b、更新的字段(如果点赞-修改点赞总数，喜欢-修改喜欢总数)
        Update update = new Update();
        if(commentType==1) {
            update.inc("likeCount",-1);
        }else if (commentType==2) {
            update.inc("commentCount",-1);
        }else {
            update.inc("loveCount",-1);
        }
        //c、更新的设置（返回最新值）
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);
        Movement modify = mongoTemplate.findAndModify(query, update, options, Movement.class);
        //3、返回互动总数（点赞，喜欢，评论）
        if(commentType==1) {
            return modify.getLikeCount();
        }else if(commentType == 2) {
            return modify.getCommentCount();
        }else {
            return modify.getLoveCount();
        }
    }
}
